package com.wx;


import com.wx.restservice.Rest;
import com.wx.util.SpringUtil;
import com.wx.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @User: Jrxsr
 * Setinterval
 * on 2019/1/2.
 **/
public class Setinterval implements Runnable {

    private String url;
    private String token;

    Rest restImpl;
    public void setRestImpl(Rest restImpl){
        this.restImpl = restImpl;
    }

    private Setinterval(){
        System.out.println("SetInterVal--构造");
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        System.out.println("传参："+url);
        this.url = url;
    }

    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }

    private static Setinterval setinterval;
    public static synchronized Setinterval getInstance() {
        if(setinterval==null) {
            setinterval = new Setinterval();
        }
        return setinterval;
    }

    @Override
    public void run() {
        this.restImpl = (Rest) SpringUtil.getBean("restImpl");
        while(true) {
            token = restful(null, url,"get");
            token = (String) Util.JSONToMap(token).get("access_token");
            System.out.println("线程调用：token="+token);
            try {
                Thread.sleep(7100000);//3600000   1小时刷新一次
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    /*
     * obj    传入参数
     * method 请求的url地址
     * req    请求方式
     */
    public String restful(Object obj, String url, String req) {
        String str=null;
        ResponseEntity entity=null;
        switch (req){
            case "get":
                if(obj==null) {
                    str = (String)restImpl.restget(url, String.class);
                }else{
                    str = (String)restImpl.restget(url, String.class, obj);
                }
                break;
            case "post":
                System.out.println("Here We Are Again POST");
                entity = (ResponseEntity) restImpl.restpost(url, obj, String.class);
                str = entity.getBody().toString();
                break;
            case "put":
                System.out.println("Here We Are Again PUT");
                str = (String)restImpl.restput(url, req);
                break;
            case "delete":
                str = (String)restImpl.restdelete(url, req);
                break;
            default: str = "未找到方法";
        }
        System.err.println(req+"请求,地址："+"["+url+"]");
        if (entity!=null){
            System.out.println("entity:"+entity.getBody().toString());
        }
        return str;
    }
}